package com.black.cat.seed.controller;

import com.black.cat.seed.common.ApiResponse;
import com.black.cat.seed.utils.FileNameUtil;
import com.black.cat.seed.vo.OSSFileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @Author blackcat
 * @create 2021/4/4 16:10
 * @version: 1.0
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {


    @PostMapping("/update")
    public ApiResponse<OSSFileVO> webUpload(@RequestParam MultipartFile file) {
        String filename = file.getOriginalFilename();
        String realName = filename.substring(0, filename.lastIndexOf("."));
        return ApiResponse.ofSuccess(webLocalUpload(file, realName + FileNameUtil.getFileName()));
    }

    private OSSFileVO webLocalUpload(MultipartFile file, String fileName) {
        try {
            String filename = file.getOriginalFilename();
            //获取后缀
            String suffix = filename.substring(filename.lastIndexOf("."));
            //获取文件名称
            String newFileName = fileName + suffix;
            String objectName = FileNameUtil.getFolder() + newFileName;
            //文件上传OSS
            String osName = System.getProperty("os.name");
            String pre = "";
            //如果是windows
            if (osName.toLowerCase().startsWith("win")) {
                pre = "C:/filedata/";
            } else {
                //linux或者mac
                pre = "/filedata/";
            }
            String dest = pre + objectName;
            File destFile = new File(dest);
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            file.transferTo(destFile);
            OSSFileVO dto = new OSSFileVO();
            dto.setFileName(newFileName)
                    .setObjectName(objectName)
                    .setPubUrl(dest);
            return dto;

        } catch (Exception e) {
            log.error("OSS文件上传失败:{}", e);
            throw new RuntimeException("OSS文件上传失败" + e.getMessage());
        }
    }

}
